<template>
  <div v-loading="loading">
    <div
      id="div_tab"
      hidden
    ></div>

    <el-row>
      <el-col style="text-align:left">
        <el-button
          type="success"
          @click="buttonClicks.addBtnClick"
        >添加</el-button>
        <!-- <el-button-group>
          <el-button
            type="primary"
            @click="buttonClicks.uploadExcelBtnClick"
          >上传Excel</el-button>
          <el-button
            type="primary"
            @click="buttonClicks.downloadExcelBtnClick"
          >下载Excel模板</el-button>
        </el-button-group> -->
        <el-button-group>
          <el-button
            type="primary"
            @click="buttonClicks.readExcelTextBtnClick(2)"
          >粘贴Excel</el-button>
          <el-button
            type="info"
            @click="buttonClicks.readExcelTextBtnClick(1)"
          >粘贴内销Excel</el-button>
          <el-button
            type="info"
            @click="buttonClicks.readExcelTextBtnClick(3)"
          >粘贴车间Excel</el-button>
        </el-button-group>
      </el-col>
      <input
        type="file"
        id="excelFileInput"
        style="display:none"
        accept=".xls,.xlsx"
        @change="buttonClicks.uploadExcelChanged"
      >
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form
          :model="dialogDatas.currentData"
          label-width="80px"
        >
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <!-- 下拉选项 -->
            <el-checkbox
              v-if="item.canHidden"
              v-model="item.isNotHidden"
              @change="buttonClicks.bcBtnClick"
            />
            <el-select
              v-model="dialogDatas.currentData[item.value]"
              v-if="item.isSelect"
              v-show="item.isNotHidden"
            >
              <el-option
                v-for="optionItem in dialogDatas.formOptions[item.selectOptionsName]"
                :key="optionItem.value"
                :label="optionItem.label"
                :value="optionItem.value"
              />
            </el-select>
            <!-- 输入框 -->
            <div
              v-else-if="!item.isDate"
              style="width:90%"
              v-show="item.isNotHidden"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.isDisabled"
              />
              <div
                style="text-align:left;color:red"
                v-show="dialogDatas.currentData.TYPE == 2"
              >
                <el-select
                  v-model="dialogDatas.currentData.PERSON.ps"
                  v-show="item.value=='ADDRESS'&& dialogDatas.currentData.PERSON"
                >
                  <el-option
                    v-for="item in dialogDatas.currentData.PERSON['ps_res']"
                    :label="item.ADDRESS+'('+item.PRICE+')'"
                    :value="item.PRICE"
                  />
                </el-select>
                <!-- <span v-show="item.value=='ADDRESS'&& dialogDatas.currentData.PERSON">
                  <span
                    @click="dialogDatas.psdjLabelClick"
                    v-if="dialogDatas.currentData.PERSON['ps_res'] && dialogDatas.currentData.PERSON['ps_res'].length"
                  >
                    地址(单价):
                    {{ dialogDatas.currentData.PERSON['ps_res'][0]['ADDRESS'] }}
                    ({{ dialogDatas.currentData.PERSON['ps_res'][0]['PRICE'] }})
                  </span>
                </span> -->

                <div v-show="item.value=='PS_COST' && dialogDatas.currentData.PERSON">
                  <el-radio-group
                    v-model="dialogDatas.currentData[item.value]"
                    v-if="dialogDatas.currentData.PERSON['zs_res'] && dialogDatas.currentData.PERSON['zs_res'].length"
                  >
                    <el-radio
                      v-for="res in dialogDatas.currentData.PERSON['zs_res']"
                      :key="res"
                      :label="res['PRICE']"
                      size="large"
                    >({{res['PRICE']}}){{res['ADDRESS']}}</el-radio>
                  </el-radio-group>

                </div>

              </div>

              <div style="text-align:left;color:red">
                <el-radio-group
                  v-model="dialogDatas.currentData['ysCostAddress']"
                  v-show="item.value=='YS_COST'"
                >
                  <el-radio
                    v-for="res in dialogDatas.currentData['ysCostAddressArr']"
                    :key="res"
                    :label="res['ADDRESS']"
                    size="large"
                  >{{res['ADDRESS']}}</el-radio>
                </el-radio-group>

              </div>
            </div>
            <!-- 日期选择 -->
            <el-date-picker
              v-else-if="item.isNotHidden"
              v-model="dialogDatas.currentData[item.value]"
              type="date"
              placeholder="Pick a Date"
              format="YYYY/MM/DD"
              value-format="YYYY/MM/DD"
            />

          </el-form-item>
        </el-form>
        <el-button
          v-show="dialogDatas.currentData.HTH"
          type="primary"
          @click="buttonClicks.addFJBtnClick()"
        >
          附件
        </el-button>
        <el-dialog
          v-model="dialogDatas.currentData.addFJ"
          title="上传附件"
          fullscreen
          append-to-body
          destroy-on-close
        >
          <div style="background-color:red;height:80vh">
            <iframe
              id="inlineFrameExample"
              title="Inline Frame Example"
              style="width: 100%;height:100%"
              :src="dialogDatas.currentData.src"
              v-if="dialogDatas.currentData.addFJ"
            >

            </iframe>

          </div>
        </el-dialog>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-row class="marginTop10">
      <el-col :span="4">
        <el-date-picker
          v-model="tableDatas.filters.date"
          type="daterange"
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY/MM/DD"
          value-format="YYYY/MM/DD"
          style="width:100%"
        />
      </el-col>
      <el-col :span="4">
        <el-checkbox-group v-model="tableDatas.filters.type">
          <el-checkbox
            :label="1"
            size="large"
          >内销</el-checkbox>
          <el-checkbox
            :label="2"
            size="large"
          >外销</el-checkbox>
        </el-checkbox-group>
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="tableDatas.filters.hth"
          placeholder="合同号"
        />
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="tableDatas.filters.khmc"
          placeholder="客户名称"
        />
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="tableDatas.filters.lxr"
          placeholder="联系人"
        />
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="tableDatas.filters.syb"
          placeholder="事业部"
        />
      </el-col>
      <el-col :span="1">
        <el-button
          @click="tableDatas.exportExcel"
          type="primary"
        >导出</el-button>
      </el-col>
      <el-col :span="1">
        <el-popover
          placement="bottom"
          trigger="click"
        >
          <template #reference>
            <el-button type="primary">导出年报表</el-button>
          </template>
          <el-date-picker
            v-model="tableDatas.exportYear"
            type="year"
            placeholder="选择年份"
            style="width:100%"
            @change="tableDatas.exportYearExcel"
            value-format="YYYY"
            :clearable="false"
          />
        </el-popover>

      </el-col>
      <!-- <el-col :span="4">
        <el-select
          v-model="tableDatas.filters.hth"
          multiple
          placeholder="Select"
          style="width: 100%"
        >
          <el-option
            v-for="item in 5"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-col> -->

    </el-row>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      :show-overflow-tooltip="true"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  v-show="deleteIds.includes(userid) || scope.row.CREATER == userid"
                >删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
        <template
          #default="scope"
          v-else
        >
          <span :style="{ 'font-size':['UPDATETIME'].includes(column.prop) ? '10px':'14px'}">
            {{ tableDatas.getTextValueFromNumber(column.prop,scope.row[column.prop]) }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination>

    <data-table-dailog-vue
      ref="dataTableDialog"
      :confirmBtnClick="buttonClicks.uploadExcelDatas"
      :cancelBtnClick="buttonClicks.uploadCancel"
    ></data-table-dailog-vue>
  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { h, onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import useMyXlsx from '@/hooks/useMyXlsx';
import { showWarning } from '@/hooks/useMyMessageBox';
import { dayjs, ElInput, ElOption, ElSelect, linkEmits } from 'element-plus';
import myAxios193 from '@/myAxios/myAxios193';
import DataTableDailogVue from './DataTableDailog.vue';
import VueCookie from 'vue-cookie';
import { read, utils } from 'xlsx';

export default {
  name: 'MainTable',
  components: {
    DataTableDailogVue,
  },
  setup () {
    let loading = ref(false);
    let dataTableDialog = ref(null);
    let deleteIds = ['3896'];
    let userid = VueCookie.get('userid');
    let buttonClicks = {
      addFJBtnClick: function () {
        // 拼接iframe链接
        let origin = window.location.origin;
        // let origin = `http://htqdds.haitian.com:9911`;
        let path = `/qdmes/SRM/LogisticsInformation_qd_appendimg.html?`;
        let query = {
          iframe: true,
          hth: dialogDatas.currentData.HTH,
          cost_id: dialogDatas.currentData.COST_ID,
          vision: Math.random(),
        };
        dialogDatas.currentData.src = origin + path + Object.keys(query).map(key => `${key}=${query[key]}`).join('&');
        dialogDatas.currentData.addFJ = true;
      },
      addBtnClick: function () {
        showFormDialog();
      },
      readExcelTextBtnClick: function (type) {
        let newRow = {};
        let sybDoms = [];
        for (let i = 0; i < dialogDatas.formOptions.sybOptions.length; i++) {
          if (type == 1) {
            sybDoms.push(h(ElOption, dialogDatas.formOptions.sybOptions[i], null));
          }
          else if ([2, 3].includes(type)) {
            // 外销/车间 的自动化科技分为 机械手 和 磁板,两者模板不同,用4.1和4.2做区分
            if (i == 3) {
              let jxs = { label: '自动化科技-机械手', value: 4.1 };
              let cb = { label: '自动化科技-磁板', value: 4.2 };
              sybDoms.push(h(ElOption, jxs, null), h(ElOption, cb, null));
            }
            else {
              sybDoms.push(h(ElOption, dialogDatas.formOptions.sybOptions[i], null));
            }
          }
        }

        let readExcelTextSyb = ref(1);

        ElMessageBox({
          title: type == 1 ? '粘贴内销内容' : (type == 2 ? '粘贴外销内容' : '粘贴车间内容'),
          message: () => h('div', null, [
            h(ElSelect, {
              modelValue: readExcelTextSyb.value,
              "onUpdate:modelValue": (val) => {
                readExcelTextSyb.value = val;
              },
            }, () => sybDoms),
            h('textarea', {
              'style': {
                width: '100%',
              },
              'rows': "5",
              'onPaste': async function (event) {
                // event里的clipboardData对象
                let clipboardDataExcelData = event.clipboardData.getData('text/html');

                let tableExp = new RegExp(/<table[\S\s]*<\/table>/g);
                let tableDom = clipboardDataExcelData.match(tableExp);
                let thIndex = tableDom[0].search('<tr');

                //内销
                let axBase1 = [
                  '所属事业部', '产品内容', '日期', '客户', '车长', '件数',
                  '合同订单号', '收货地址', '联系人及电话', '重量', '配送费',
                ];
                let ths1 = [
                  [...axBase1],
                  [...axBase1],
                  [...axBase1],
                  [...axBase1],
                ];

                //外销
                //1: 安信事业部 2:精密 3:液压传动事业部 4.1:自动化科技-机械手,4.2:自动化科技-磁板
                let axBase2 = [
                  '所属事业部', '木箱型号', '数量', '日期', '物料号',
                  '物料描述', '数量', '单位', '客户', '合同订单号',
                  '收货地址', '流水号', '销售出库单号', '联系人及电话', '发件方式', '服务方式',
                  '件数', '重量', '运输费用', '直送费', '总金额',
                  '包装费用', '单产品分类', '物流单号',
                  '业务员',
                ];
                let ths2 = {
                  1: [...axBase2],
                  2: [
                    '所属事业部', '日期', '物料号', '物料描述', '数量',
                    '单位', '销售出库单号', '客户',
                    '收货地址',//表格上是 客户地址
                    '合同订单号', '联系人及电话', '提货方式', '服务方式',
                    '件数', '重量', '运输费',
                    '直送费', '总金额', '单号',
                    '业务员',
                  ],
                  3: [
                    '所属事业部', '业务员', '日期', '客户', '收货地址',
                    '联系人', '电话', '发件方式', '服务方式', '备注', '物料号',
                    '物料描述', '发货数量', '库存', '合同订单号', '销售出库单号',
                    '流水号', '件数', '重量', '运输费', '直送费',
                    '木箱型号', '数量', '单产品分类',
                    '业务员1',
                  ],
                  // 4.1: [
                  //   '所属事业部', '日期', '物料号', '编码', '物料描述',
                  //   '客户', '收货地址', '合同订单号', '塑机订单', '数量',
                  //   '退回数量', '单位', '销售出库单号', '流水号', '联系人及电话',
                  //   '发件方式', '运费', '直送', '其他', '总金额',
                  //   '业务员',
                  // ],
                  // 4.2: [
                  //   '所属事业部', '日期', '物料号', '客户', '物料描述',
                  //   '收货地址', '合同订单号', '塑机订单', '数量', '退回数量',
                  //   '单位', '销售出库单号', '流水号', '联系人及电话', '发件方式',
                  //   '运费', '直送', '其他', '总金额',
                  //   '业务员',
                  // ],

                  // 自动化科技 用 液压传动的模板 朱凤君(4760) 2024/12/23
                  4.1: [
                    '所属事业部', '业务员', '日期', '客户', '收货地址',
                    '联系人', '电话', '发件方式', '服务方式', '备注', '物料号',
                    '物料描述', '发货数量', '库存', '合同订单号', '销售出库单号',
                    '流水号', '件数', '重量', '运输费', '直送费',
                    '木箱型号', '数量', '单产品分类',
                    '业务员1',
                  ],
                  4.2: [
                    '所属事业部', '业务员', '日期', '客户', '收货地址',
                    '联系人', '电话', '发件方式', '服务方式', '备注', '物料号',
                    '物料描述', '发货数量', '库存', '合同订单号', '销售出库单号',
                    '流水号', '件数', '重量', '运输费', '直送费',
                    '木箱型号', '数量', '单产品分类',
                    '业务员1',
                  ],
                };

                //车间
                let axBase3 = [
                  '所属事业部', '快递公司', '产品内容', '日期', '收货地址', '联系人及电话',
                  '发件方式', '车长', '件数', '重量', '运费', '送货费', '业务员',
                ];
                let ths3 = [
                  [...axBase3],
                ];



                let thDom = `<tr>`;
                if (type == 1) {
                  ths1[readExcelTextSyb.value - 1].forEach(key => {
                    thDom += `<th>${key}</th>`;
                  });
                }
                else if ([2].includes(type)) {
                  ths2[readExcelTextSyb.value].forEach(key => {
                    thDom += `<th>${key}</th>`;
                  });
                }
                else if ([3].includes(type)) {
                  ths3[readExcelTextSyb.value - 1].forEach(key => {
                    thDom += `<th>${key}</th>`;
                  });
                }
                thDom += `</tr>`;
                tableDom[0] = tableDom[0].slice(0, thIndex) + thDom + tableDom[0].slice(thIndex);

                document.getElementById('div_tab').innerHTML = tableDom[0];
                let sheet = utils.table_to_sheet(document.getElementsByTagName('table')[0], {});
                let jsonDatas = utils.sheet_to_json(sheet);
                console.log('json :>> ', jsonDatas);

                newRow = { ...dialogDatas.oriNewData };
                newRow.COST_ID = v4();

                newRow.TYPE = type;
                newRow.SYB = tableDatas.getNumberValueFromText('SYB', jsonDatas[0]['所属事业部']);
                let hthArr = Array.from(new Set(jsonDatas.map(item => item['合同订单号'])));
                newRow.HTH = hthArr.join(',');
                newRow.ADDRESS = jsonDatas[0]['收货地址'];

                let xlsx = useMyXlsx();
                newRow.REDATE = xlsx.formatDate(jsonDatas[0]['日期']);

                //内销
                if (type == 1) {
                  newRow.PRODUCT = tableDatas.getNumberValueFromText('PRODUCT', jsonDatas[0]['产品内容']);
                }

                //外销
                if ([2].includes(type)) {
                  // 安信 把 物流单号 变成 产品备注
                  if (readExcelTextSyb.value == 1) {
                    // jsonDatas[0]['联系人及电话'] = jsonDatas[0]['联系人'] + ' ' + jsonDatas[0]['电话'];
                    newRow.PRODUCT_TEXT = jsonDatas[0]['物流单号'];
                    newRow.KD_SERVER = jsonDatas[0]['服务方式'];
                  }
                  // 精密 把单号变成产品备注
                  if (readExcelTextSyb.value == 2) {
                    // jsonDatas[0]['联系人及电话'] = jsonDatas[0]['联系人'] + ' ' + jsonDatas[0]['电话'];
                    newRow.PRODUCT_TEXT = jsonDatas[0]['单号'];
                    newRow.KD_SERVER = jsonDatas[0]['服务方式'];
                  }
                  // 液压传动事业部 用 联系人 + 电话
                  if (readExcelTextSyb.value == 3) {
                    jsonDatas[0]['联系人及电话'] = jsonDatas[0]['联系人'] + ' ' + jsonDatas[0]['电话'];
                    newRow.PRODUCT_TEXT = jsonDatas[0]['发件方式'];
                    newRow.KD_SERVER = jsonDatas[0]['服务方式'];
                  }
                  //外销的自动化科技分为 机械手 和 磁板,两者模板不同,用4.1和4.2做区分,Math.floor获取给定数字(4.1)的整数(4)
                  else if (Math.floor(readExcelTextSyb.value) == 4) {
                    // let sum = jsonDatas.reduce((pre, cur) => {
                    //   return Number(pre ? pre : 0) + Number(cur['数量']);
                    // }, 0);
                    // jsonDatas[0]['件数'] = sum;
                    // newRow.INPUT_SUM_COST = Number(jsonDatas[0]['总金额']);

                    //自动化科技 用液压传动的模板 朱凤君(4760) 2024/12/23
                    jsonDatas[0]['联系人及电话'] = jsonDatas[0]['联系人'] + ' ' + jsonDatas[0]['电话'];
                    newRow.PRODUCT_TEXT = jsonDatas[0]['发件方式'];
                    newRow.KD_SERVER = jsonDatas[0]['服务方式'];
                  }
                  newRow.YWY = jsonDatas[0]['业务员'];
                }

                // 车间
                if ([3].includes(type)) {
                  newRow.PRODUCT = tableDatas.getNumberValueFromText('PRODUCT', jsonDatas[0]['产品内容']);
                  newRow.PRODUCT_TEXT = jsonDatas[0]['产品内容'];
                  newRow.YWY = jsonDatas[0]['业务员'];
                }

                newRow.CONNECT_WAY = jsonDatas[0]['联系人及电话'];

                newRow.KHMC = jsonDatas[0]['客户'];

                newRow.WEIGHT = jsonDatas[0]['重量'] ? jsonDatas[0]['重量'] : 0;
                newRow.CAR_COUNT = jsonDatas[0]['件数'];
                newRow.CAR_LENGTH = [1, 3].includes(type) ? (jsonDatas[0]['车长'] ? String(jsonDatas[0]['车长']) : '') : '';
                if ([1].includes(type)) {
                  newRow.PS_COST = jsonDatas[0]['配送费'] ? Number(jsonDatas[0]['配送费']) : '';
                }
                if ([3].includes(type)) {
                  newRow.PS_COST = jsonDatas[0]['送货费'] ? Number(jsonDatas[0]['送货费']) : '';
                  newRow.YS_COST = jsonDatas[0]['运费'] ? Number(jsonDatas[0]['运费']) : '';
                }

                //外销 要获取直送费和单价等信息
                if ([2].includes(type)) {

                  // let person = smart(jsonDatas[0]['收货地址'] + ' ' + jsonDatas[0]['联系人及电话']);
                  let dataContent = JSON.stringify({ "address": jsonDatas[0]['收货地址'] + ' ' + jsonDatas[0]['联系人及电话'] });
                  let person = (await myAxios193.get('pszx/getAddressInfo', dataContent)).data;
                  console.log('person :>> ', person);

                  if (!person.person) {
                    var reg = new RegExp(/\D{2,3}/g);
                    let resultArr = jsonDatas[0]['联系人及电话'].match(reg);
                    if (resultArr.length) {
                      person.person = resultArr[0];
                    }
                  }
                  if (!person.county)
                    person.county = '';
                  let ps_params = `${person.province.replaceAll(/[省市]/g, '')}\t${person.city.replaceAll(/[区市]/g, '')}`
                    + `\t${person.county.replaceAll(/[区市县]/g, '')}\t${person.town.replaceAll(/[乡镇]/g, '')}`;
                  let ps_res = await myAxios.get('陈帅廷查询配送中心配送费', ps_params);
                  if (ps_res.length > 0) {
                    person.ps_res = ps_res;
                    person.ps = ps_res[0].PRICE;
                  }
                  else {
                    person.ps_res = [];
                    person.ps = 0;
                  }
                  let zs_params = `${person.person}\t${person.phonenum}`;
                  let zs_res = await myAxios.get('陈帅廷查询配送中心直送费', zs_params);
                  if (zs_res.length > 0) {
                    person.zs_res = zs_res;
                    dialogDatas.currentData.PS_COST = zs_res[0]['PRICE'];
                  }
                  else {
                    person.zs_res = [];
                  }
                }

              },
            }, null)
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then((action) => {
          showFormDialog(newRow);
        }).catch(err => {
          console.log('err :>> ', err);
        });
      },
      bcBtnClick: function (value) {
        updateOutComputeWay(value);
      },
      //#region  excel文件读取
      downloadExcelBtnClick: function () {
        let url = "http://192.168.100.30:9091/QDMES/CHER/pszx_delivery_cost/配送中心物流运输费.xlsx";
        let a = document.createElement('a');
        a.href = url;
        a.click();
      },
      uploadExcelBtnClick: function () {
        document.querySelector('#excelFileInput').click();
      },
      uploadExcelChanged: async function ({ srcElement }) {
        if (srcElement.files.length) {
          let xlsx = useMyXlsx();
          let excelDatas = await xlsx.getDataFromExcel(srcElement.files[0]);
          let requestParamsArr = [];
          console.log('excelDatas :>> ', excelDatas);
          let tableUIDatas = {
            tableDatas: excelDatas[0],
            columns: Object.keys(excelDatas[0][0]).map(key => {
              return {
                key: key,
                title: key,
                dataKey: key,
                align: 'center',
                width: 100,
              };
            })
          };
          dataTableDialog.value.showTableDialog('Excel数据', tableUIDatas);
          document.getElementById("excelFileInput").value = null;
        }
      },
      uploadExcelDatas: function (dialogUIDatas) {
        let excelDatas = dialogUIDatas.tableUIDatas.tableDatas;
        let requestParamsArr = [];
        for (let i = 0; i < excelDatas.length; i++) {
          let item = excelDatas[i];
          let addressArr = item['收货地址'].split('、');
          for (let i = 0; i < addressArr.length; i++) {
            const address = addressArr[i];

            // let person = smart(jsonDatas[0]['联系人及电话']);
            // console.log('person :>> ', person);
            let params = `${address}\t${item['SYB']}\t${item['NAME']}`
              + `\t${item['PHONE']}\t${item['PRICE']}`;

            params = params.replaceAll('null', '').replaceAll('undefined', '');
            requestParamsArr.push(params);
          }


        }
        console.log('requestParamsArr :>> ', requestParamsArr);
        let requestObj = {
          "requestName": "陈帅廷添加配送中心配送费单价",
          "requestParamsArr": requestParamsArr,
          "requestFactory": "9900"
        };
        myAxios193.post('users/postMutipleRequests', JSON.stringify(requestObj)).then(res => {
          if (res.returnData.message == '全部成功' && res.returnData.status == 200) {
            dataTableDialog.value.dialogUIDatas.loading = false;
            dataTableDialog.value.closeTableDialog();
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交全部成功!'
            });
            getTableDatas();
          }
          else if (res.returnData.message == '部分失败') {
            dataTableDialog.value.dialogUIDatas.loading = false;
            showWarning('提交部分失败!' + res.returnData.resultArr.join(',,,,,'));
          }
        });
      },
      uploadCancel: function () {
        dataTableDialog.value.dialogUIDatas.loading = false;
        dataTableDialog.value.closeTableDialog();
        getTableDatas();
      }
      //#endregion

    };

    let showFormDialog = function (row) {
      dialogDatas.isNew = row ? false : true;
      let newRow = row ? row : dialogDatas.oriNewData;
      newRow.INPUT_SUM_COST = newRow.INPUT_SUM_COST ? newRow.INPUT_SUM_COST : (newRow.SUM_COST ? newRow.SUM_COST : 0);
      dialogDatas.currentData = { INPUT_SUM_COST: 0, ...newRow, };
      //内销包车
      if (dialogDatas.currentData.TYPE == 1) {
        dialogDatas.currentData.PS_COST = dialogDatas.currentData.PS_COST ? dialogDatas.currentData.PS_COST : 0;
        dialogDatas.currentData.ysCostAddressArr = computed(() => {
          //先用地址,再用客户名称
          if (dialogDatas.currentData.ADDRESS) {
            console.log('dialogDatas.currentData.ADDRESS :>> ', dialogDatas.currentData.ADDRESS);
            let addressArr = tableDatas.bcDatas.filter(item =>
              item['INSTATE'] == 1
              && item['ADDRESS']
              && item['ADDRESS'].includes(dialogDatas.currentData.ADDRESS)
              && item['SYB'] == dialogDatas.currentData.SYB
            );
            if (addressArr.length)
              dialogDatas.currentData.ysCostAddress = addressArr[0]['ADDRESS'];
            return addressArr;
          }
          else if (dialogDatas.currentData.KHMC) {
            console.log('dialogDatas.currentData.KHMC :>> ', dialogDatas.currentData.KHMC);
            let addressArr = tableDatas.bcDatas.filter(item =>
              item['INSTATE'] == 1
              && item['KHMC']
              && item['KHMC'].includes(dialogDatas.currentData.KHMC)
              && item['SYB'] == dialogDatas.currentData.SYB
            );
            if (addressArr.length)
              dialogDatas.currentData.ysCostAddress = addressArr[0]['ADDRESS'];
            return addressArr;
          }
          else {
            return [];
          }
        });
      }
      //外销
      else if ([2].includes(dialogDatas.currentData.TYPE)) {
        updateOutComputeWay(false);
      }
      dialogDatas.dialogFormVisible = true;

      if (dialogDatas.currentData.TYPE == 3) {
        // dialogDatas.currentData.YS_COST = 0;
        dialogDatas.currentData.INPUT_SUM_COST = dialogDatas.currentData.YS_COST + dialogDatas.currentData.PS_COST;
        return;
      }

      dialogDatas.currentData.YS_COST = computed({
        get: () => {
          let selectItem = dialogDatas.formItems.find(item => item.value == 'CAR_LENGTH');
          if (selectItem.isNotHidden) {

            let key = '';
            switch (dialogDatas.currentData.CAR_LENGTH) {
              case '4.2': key = 'COST4_2'; break;
              case '6.2': key = 'COST6_2'; break;
              case '6.8': key = 'COST6_8'; break;
              case '9.6': key = 'COST9_6'; break;
              case '13': key = 'COST13'; break;
              case '17.5': key = 'COST17_5'; break;
              default: break;
            }
            let countReg = new RegExp(/\d+/g);
            let numArr = [0];
            if (dialogDatas.currentData.CAR_COUNT) {
              numArr = String(dialogDatas.currentData.CAR_COUNT).match(countReg);
            }

            if (key && numArr.length) {
              let addressArr = tableDatas.bcDatas.filter(item =>
                item['ADDRESS'] == dialogDatas.currentData.ysCostAddress
                && item['SYB'] == dialogDatas.currentData.SYB
                && item['INSTATE'] == dialogDatas.currentData.TYPE);
              console.log('addressArr :>> ', addressArr);
              if (addressArr.length) {
                return Number(addressArr[0][key]) * Number(numArr[0]);
              }
              else {
                return 0;
              }
            }
            else {
              return 0;
            }
          }
          else {
            //通宇运输费系统自动计算
            if (dialogDatas.currentData.KD_TYPE == 0) {
              try {
                return (Number(dialogDatas.currentData.WEIGHT) * dialogDatas.currentData.PERSON.ps).toFixed(2);
              }
              catch {
                return (Number(dialogDatas.currentData.WEIGHT) * 0).toFixed(2);
              }
            }
            //其他快递公司运输费固定0
            else {
              return 0.00;
            }
          }
        },
        set () {

        }
      });

      dialogDatas.currentData.SUM_COST = computed(() => {
        return (Number(dialogDatas.currentData.YS_COST) + Number(dialogDatas.currentData.PS_COST)).toFixed(2);
      });

    };

    let formOptionTexts = {
      //产品 -1:其他 1: 马达 2:电机 3:驱动器 4:阀 5:导轨 6:机械手 7:磁板 8:驱动器+泵 9:电机+泵 10:电机+驱动器+泵 11:泵 12:电线
      productOptionText: '其他,马达,电机,驱动器,阀,导轨,机械手,磁板,驱动器+泵,电机+泵,电机+驱动器+泵,泵,电线',
      //事业部 1: 安信事业部 2:精密 3:液压传动事业部 4:自动化科技
      sybOptionText: '安信事业部,精密,液压传动事业部,自动化科技',
      //车长 4.2，6.2，6.8，9.6，13，17.5
      clOptionText: '4.2,6.2,6.8,9.6,13,17.5',
      //件数 1车，2车，3车
      ccOptionText: '1车,2车,3车',
      //快递类型 0:通宇 1:顺丰 2:申通 3:跨越 4:韵达 5:吉速 6:百世
      kdTypeOptionText: '通宇,顺丰,申通,跨越,韵达,吉速,百世',
      //快递服务
      kdServerOptionText: `隔日达,同城次日,省内次日,整车运输,陆运件`,
    };
    let dialogDatas = reactive({
      dialogFormVisible: false,
      oriNewData: {
        COST_ID: '',
        PRODUCT: -1,
        PRODUCT_TEXT: '',
        SYB: 1,
        CAR_LENGTH: '4.2',
        CAR_COUNT: '0',
        HTH: '',
        ADDRESS: '',
        CONNECT_WAY: '',
        WEIGHT: '',
        YS_COST: 0,
        PS_COST: 0,
        SUM_COST: 0,
        TYPE: 1,
        INPUT_SUM_COST: 0,
        KD_TYPE: 0,
        KHMC: '',
        PERSON: {
          ps: 0,
          ps_res: [],
          zs_res: [],
        },
        ysCostAddress: '',
        ysCostAddressArr: [],
      },
      currentData: {},
      isNew: false,
      formOptions: {
        productOptions: formOptionTexts.productOptionText.split(',').map((text, index) => {
          return {
            value: index == 0 ? -1 : index,
            label: text
          };
        }),
        sybOptions: formOptionTexts.sybOptionText.split(',').map((text, index) => {
          return {
            value: index + 1,
            label: text
          };
        }),
        clOptions: formOptionTexts.clOptionText.split(',').map((text, index) => {
          return {
            value: text,
            label: text
          };
        }),
        //件数 1车，2车，3车
        ccOptions: formOptionTexts.ccOptionText.split(',').map((text, index) => {
          return {
            value: text,
            label: text
          };
        }),
        //类型 1:内销 2:外销
        typeOptions: [
          {
            value: 1,
            label: '内销'
          },
          {
            value: 2,
            label: '外销'
          },
          {
            value: 3,
            label: '车间'
          },
        ],
        kdTypeOptions: formOptionTexts.kdTypeOptionText.split(',').map((text, index) => {
          return {
            value: index,
            label: text,
          };
        }),
        kdServerOptions: formOptionTexts.kdServerOptionText.split(',').map((text, index) => {
          return {
            value: text,
            label: text,
          };
        }),

      },
      formItems: [
        {
          "value": "TYPE",
          "label": "类型",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'typeOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "REDATE",
          "label": "出运日期",
          "isDate": true,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "KD_TYPE",
          "label": "快递类型",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'kdTypeOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "KD_SERVER",
          "label": "快递服务",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'kdServerOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "PRODUCT",
          "label": "产品",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'productOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "KHMC",
          "label": "客户名称",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "PRODUCT_TEXT",
          "label": "产品备注",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "SYB",
          "label": "事业部",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'sybOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "CAR_LENGTH",
          "label": "车长",
          "isDate": false,
          "isSelect": true,
          "selectOptionsName": 'clOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "CAR_COUNT",
          "label": "件数",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": 'ccOptions',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "HTH",
          "label": "合同号",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "ADDRESS",
          "label": "地址",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "YWY",
          "label": "业务员",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "CONNECT_WAY",
          "label": "联系人",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "WEIGHT",
          "label": "重量",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "YS_COST",
          "label": "运输费",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "PS_COST",
          "label": "配送费",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
        },
        {
          "value": "SUM_COST",
          "label": "总费用",
          "isDate": false,
          "isSelect": false,
          "selectOptionsName": '',
          "canHidden": false,
          "isNotHidden": true,
          "isDisabled": true
        },
      ],
      confirmBtnClick: function () {
        loading.value = true;

        let now = dayjs().format('YYYY/MM/DD HH:mm:ss');
        let REDATE = dialogDatas.currentData.REDATE ? dialogDatas.currentData.REDATE : now.slice(0, 10);
        let SUM_COST = 0;
        let YS_COST = 0;
        let PS_COST = 0;
        // 如果是内外销,运费自动计算,如果是其他,运费手动输入
        if ([1, 2].includes(dialogDatas.currentData.TYPE)) {
          //如果是通宇,费用自动计算,如果是其他,配送费和运送费都为0,总价手动输入
          SUM_COST = dialogDatas.currentData.KD_TYPE == 0 ? dialogDatas.currentData.SUM_COST : dialogDatas.currentData.INPUT_SUM_COST;
          YS_COST = dialogDatas.currentData.KD_TYPE == 0 ? dialogDatas.currentData.YS_COST : 0;
          PS_COST = dialogDatas.currentData.KD_TYPE == 0 ? dialogDatas.currentData.PS_COST : 0;
        }
        else {
          SUM_COST = dialogDatas.currentData.INPUT_SUM_COST;
          YS_COST = dialogDatas.currentData.YS_COST;
          PS_COST = dialogDatas.currentData.PS_COST;
        }


        let workid = VueCookie.get('userid');

        let params = `${dialogDatas.isNew ? v4() : dialogDatas.currentData.COST_ID}\t${dialogDatas.currentData.PRODUCT}\t${dialogDatas.currentData.PRODUCT_TEXT}`
          + `\t${dialogDatas.currentData.SYB}\t${dialogDatas.currentData.CAR_LENGTH}\t${dialogDatas.currentData.CAR_COUNT}`
          + `\t${dialogDatas.currentData.HTH}\t${dialogDatas.currentData.ADDRESS}\t${dialogDatas.currentData.CONNECT_WAY}`
          + `\t${dialogDatas.currentData.WEIGHT}\t${YS_COST}\t${PS_COST}`
          + `\t${SUM_COST}\t${dialogDatas.currentData.TYPE}\t${now}`
          + `\t${REDATE}\t${dialogDatas.currentData.KD_TYPE}\t${dialogDatas.currentData.KHMC}`
          + `\t${workid}\t${dialogDatas.currentData.YWY}\t${dialogDatas.currentData.KD_SERVER}`;

        myAxios.post('陈帅廷添加或修改配送中心快递信息', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    watch(() => dialogDatas.currentData.TYPE, (newV, oldV) => {
      if (newV == 1) {
        let carLengthItem = dialogDatas.formItems.find(item => item.value == 'CAR_LENGTH');
        carLengthItem.canHidden = false;
        carLengthItem.isNotHidden = true;
        let carCountItem = dialogDatas.formItems.find(item => item.value == 'CAR_COUNT');
        carCountItem.canHidden = false;
        carCountItem.isNotHidden = true;
      }
      else {
        let carLengthItem = dialogDatas.formItems.find(item => item.value == 'CAR_LENGTH');
        carLengthItem.canHidden = true;
        carLengthItem.isNotHidden = false;
        let carCountItem = dialogDatas.formItems.find(item => item.value == 'CAR_COUNT');
        carCountItem.canHidden = true;
        carCountItem.isNotHidden = false;
      }
    });

    watch(() => dialogDatas.currentData.KD_TYPE, (newV, oldV) => {
      if (newV == 0) {
        if (dialogDatas.currentData.SYB == 4 || dialogDatas.currentData.TYPE == 3) {
          let sumCostItem = dialogDatas.formItems.find(item => item.value == 'SUM_COST');
          if (sumCostItem) {
            sumCostItem.isDisabled = false;
            sumCostItem.value = 'INPUT_SUM_COST';
          }
        }
        else {
          let sumCostItem = dialogDatas.formItems.find(item => item.value == 'INPUT_SUM_COST');
          if (sumCostItem) {
            sumCostItem.isDisabled = true;
            sumCostItem.value = 'SUM_COST';
          }
        }
      }
      else {
        let sumCostItem = dialogDatas.formItems.find(item => item.value == 'SUM_COST');
        if (sumCostItem) {
          sumCostItem.isDisabled = false;
          sumCostItem.value = 'INPUT_SUM_COST';
        }
      }
    }, {
      immediate: true,
    });

    let updateOutComputeWay = async function (value) {
      //外销包车
      if (value) {
        dialogDatas.currentData.PS_COST = 0;
        dialogDatas.currentData.ysCostAddressArr = computed(() => {
          let addressArr = [];
          //先用地址,再用联系人
          if (dialogDatas.currentData.ADDRESS) {
            addressArr = tableDatas.bcDatas.filter(item =>
              item['INSTATE'] == 2
              && item['ADDRESS']
              && item['ADDRESS'].includes(dialogDatas.currentData.ADDRESS)
              && item['SYB'] == dialogDatas.currentData.SYB
            );
            if (addressArr.length) {
              dialogDatas.currentData.ysCostAddress = addressArr[0]['ADDRESS'];
            }
          }
          if (addressArr.length != 0) {
            return addressArr;
          }
          else {
            if (dialogDatas.currentData.CONNECT_WAY) {
              addressArr = tableDatas.bcDatas.filter(item =>
                item['INSTATE'] == 2
                && item['CONNECT_WAY']
                && item['CONNECT_WAY'].includes(dialogDatas.currentData.CONNECT_WAY)
                && item['SYB'] == dialogDatas.currentData.SYB
              );
              if (addressArr.length)
                dialogDatas.currentData.ysCostAddress = addressArr[0]['ADDRESS'];
              return addressArr;
            }
            else {
              return addressArr;
            }
          }
        });
      }
      //外销
      else {
        let dataContent = JSON.stringify({ "address": dialogDatas.currentData.ADDRESS + ' ' + dialogDatas.currentData.CONNECT_WAY });
        let person = (await myAxios193.get('pszx/getAddressInfo', dataContent)).data;
        if (!person.person) {
          var reg = new RegExp(/\D{2,3}/g);
          let resultArr = dialogDatas.currentData.CONNECT_WAY.match(reg);
          if (resultArr.length) {
            person.person = resultArr[0];
          }
        }
        if (!person.county)
          person.county = '';

        let ps_params = `${person.province.replaceAll(/[省市]/g, '')}\t${person.city.replaceAll(/[区市]/g, '')}`
          + `\t${person.county.replaceAll(/[区市县]/g, '')}\t${person.town.replaceAll(/[乡镇]/g, '')}`;
        let ps_res = await myAxios.get('陈帅廷查询配送中心配送费', ps_params);
        person.ps_res = ps_res;
        person.ps = ps_res.length ? ps_res[0].PRICE : 0;

        let zs_params = `${person.person}\t${person.phonenum}`;
        let zs_res = await myAxios.get('陈帅廷查询配送中心直送费', zs_params);
        if (zs_res.length > 0) {
          person.zs_res = zs_res;
        }
        else {
          person.zs_res = [];
        }
        dialogDatas.currentData.PERSON = person;
      }
    };

    let getTableDatas = function () {
      loading.value = true;

      let startDate = dayjs(tableDatas.filters.date[0]).format('YYYY/MM/DD');
      let endDate = tableDatas.filters.date[1];
      let params = `${startDate}\t${endDate}`;
      myAxios.get('陈帅廷查询配送中心快递信息', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          res.forEach(item => {
            item.PERSON = {};
          });
          tableDatas.oritableData = [...res];

          ElMessage({
            showClose: true,
            type: 'success',
            message: '最新数据获取成功!'
          });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };
    let getBcDatas = function () {
      loading.value = true;

      let params = ``;
      myAxios.get('陈帅廷查询配送中心包车费', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.bcDatas = res;
        }
        else {
          loading.value = false;
          console.log('陈帅廷查询配送中心包车费 获取数据失败res!', res);
        }
      }).catch((err) => {
        loading.value = false;
        console.log('陈帅廷查询配送中心包车费 err!', err);
      });
    };

    onMounted(() => {
      getTableDatas();
      getBcDatas();
    });

    let tableDatas = reactive({
      filters: {
        date: [dayjs().add(-3, 'month').format('YYYY/MM/DD'), dayjs().format('YYYY/MM/DD')],
        type: [1, 2, 3],
        hth: '',
        khmc: '',
        lxr: '',
        syb: '',

        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableColumns: [
        {
          "prop": "TYPE",
          "label": "类型",
          "align": "center",
          "width": 60,
          // "filters": [
          //   {
          //     text: '内销',
          //     value: 1,
          //   },
          //   {
          //     text: '外销',
          //     value: 2,
          //   },
          // ],
          // "filterMethod": (value, row, column) => {
          //   return row['TYPE'] == value;
          // },
        },
        {
          "prop": "REDATE",
          "label": "出运日期",
          "align": "center",
          "width": 120,
        },
        {
          "prop": "PRODUCT",
          "label": "产品",
          "align": "center",
        },
        {
          "prop": "KD_TYPE",
          "label": "快递",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "KD_SERVER",
          "label": "服务方式",
          "align": "center",
          "width": 130,
        },
        {
          "prop": "KHMC",
          "label": "客户名称",
          "align": "center"
        },
        {
          "prop": "PRODUCT_TEXT",
          "label": "产品备注",
          "align": "center"
        },
        {
          "prop": "SYB",
          "label": "事业部",
          "align": "center",
          "width": 130,
        },
        {
          "prop": "CAR_LENGTH",
          "label": "车长",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "CAR_COUNT",
          "label": "件数",
          "align": "center",
          "width": 60,
        },
        {
          "prop": "HTH",
          "label": "合同号",
          "align": "center"
        },
        {
          "prop": "ADDRESS",
          "label": "地址",
          "align": "center"
        },
        {
          "prop": "CONNECT_WAY",
          "label": "联系人",
          "align": "center"
        },
        {
          "prop": "WEIGHT",
          "label": "重量",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "YS_COST",
          "label": "运输费",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "PS_COST",
          "label": "配送费",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "SUM_COST",
          "label": "总费用",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "YWY",
          "label": "业务员",
          "align": "center",
          "width": 90,
        },
        {
          "prop": "UPDATETIME",
          "label": "更新时间",
          "align": "center",
          "width": 130,
        },
        {
          "prop": "operate",
          "label": "操作",
          "align": "center",
          "width": 170,
        },
      ],
      getTextValueFromNumber: function (key, value) {
        if (key == 'PRODUCT') {
          let productOption = dialogDatas.formOptions.productOptions.find(option => option.value == value);
          if (productOption)
            return productOption.label;
          else
            return '';
        }
        else if (key == 'SYB') {
          let sybOption = dialogDatas.formOptions.sybOptions.find(option => option.value == value);
          if (sybOption)
            return sybOption.label;
          else
            return '';
        }
        else if (key == 'TYPE') {
          let typeOption = dialogDatas.formOptions.typeOptions.find(option => option.value == value);
          if (typeOption)
            return typeOption.label;
          else
            return '';
        }
        else if (key == 'KD_TYPE') {
          let typeOption = dialogDatas.formOptions.kdTypeOptions.find(option => option.value == value);
          if (typeOption)
            return typeOption.label;
          else
            return '';
        }
        else {
          return value;
        }
      },
      getNumberValueFromText: function (key, text) {
        if (key == 'PRODUCT') {
          let productOption = dialogDatas.formOptions.productOptions.find(option => option.label == text);
          if (productOption)
            return productOption.value;
          else
            return -2;
        }
        else if (key == 'SYB') {
          let sybOption = dialogDatas.formOptions.sybOptions.find(option => option.label == text);
          if (sybOption)
            return sybOption.value;
          else
            return -2;
        }
        else if (key == 'TYPE') {
          let typeOption = dialogDatas.formOptions.typeOptions.find(option => option.label == text);
          if (typeOption)
            return typeOption.label;
          else
            return -2;
        }
        else if (key == 'KD_TYPE') {
          let typeOption = dialogDatas.formOptions.kdTypeOptions.find(option => option.label == text);
          if (typeOption)
            return typeOption.value;
          else
            return -2;
        }
        else {
          return text;
        }
      },
      oritableData: [],
      tableDatasAfterFilter: computed(() => {
        let fData = [...tableDatas.oritableData];
        if (tableDatas.filters.type) {
          let type = tableDatas.filters.type;
          fData = fData.filter(item => type.includes(item.TYPE));
        }

        if (tableDatas.filters.date) {
          let date = tableDatas.filters.date;
          fData = fData.filter(item => item.REDATE >= date[0] && item.REDATE <= date[1]);
        }

        if (tableDatas.filters.hth) {
          let hth = tableDatas.filters.hth;
          fData = fData.filter(item => item.HTH && item.HTH.includes(hth));
        }

        if (tableDatas.filters.khmc) {
          let khmc = tableDatas.filters.khmc;
          fData = fData.filter(item => {
            if (item.KHMC) {
              return item.KHMC.includes(khmc);
            }
            else {
              return false;
            }
          });
        }

        if (tableDatas.filters.lxr) {
          let lxr = tableDatas.filters.lxr;
          fData = fData.filter(item => {
            if (item.CONNECT_WAY) {
              return item.CONNECT_WAY.includes(lxr);
            }
            else {
              return false;
            }
          });
        }

        if (tableDatas.filters.syb) {
          let syb = tableDatas.filters.syb;
          fData = fData.filter(item => {
            if (item.SYB) {

              return tableDatas.getTextValueFromNumber('SYB', item.SYB).includes(syb);
            }
            else {
              return false;
            }
          });
        }


        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;

        fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = `${row.COST_ID}`;
        myAxios.post('陈帅廷删除配送中心快递信息', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
      exportExcel: function () {
        if (!tableDatas.tableDatasAfterFilter.length) {
          showWarning('空数据无法导出!');
        }
        let data = [];
        tableDatas.tableDatasAfterFilter.forEach(item => {
          let newItem = { ...item };
          Object.keys(newItem).forEach(key => {
            newItem[key] = tableDatas.getTextValueFromNumber(key, newItem[key]);
          });
          data.push(newItem);
        });
        let xlsx = useMyXlsx();

        let exportOption = {
          titles: {},
          header: [],
          hideColumns: [],
        };
        for (let i = 0; i < tableDatas.tableColumns.length; i++) {
          let column = tableDatas.tableColumns[i];
          exportOption.titles[column.prop] = column.label;
          exportOption.header.push(column.prop);
        }
        exportOption.hideColumns = Object.keys(data[0]).filter(key => !exportOption.header.includes(key));
        let now = dayjs().format('YYYY-MM-DD HH-mm-ss');
        xlsx.exportDatas(data, exportOption, now + '.xlsx');
      },
      exportYear: '',
      exportYearExcel: function (e) {
        console.log('e :>> ', e);
        myAxios.get('陈帅廷查询配送中心年报表', `${tableDatas.exportYear}`).then(res => {
          console.log('res :>> ', res);
          if (res instanceof Array) {
            let data = [];
            res.forEach(item => {
              let newItem = { ...item };
              Object.keys(newItem).forEach(key => {
                newItem[key] = tableDatas.getTextValueFromNumber(key, newItem[key]);
              });
              data.push(newItem);
            });
            //#region 数据处理

            //#region 安信事业部

            // 安信事业部的先分内外销
            let axDatas = data.filter(el => el.SYB == '安信事业部');
            let axResultDatas = [];
            // 安信内销,只要电机和驱动器
            let axInDatas = axDatas.filter(el => el.TYPE == '内销');
            for (let i = 0; i < axInDatas.length; i++) {
              if (axInDatas[i].PRODUCT == '电机') {
                axResultDatas.push(axInDatas[i]);
              }
              else if (axInDatas[i].PRODUCT == '驱动器') {
                axResultDatas.push(axInDatas[i]);
              }
            }
            // 安信外销,全都加起来
            let axOutDatas = axDatas.filter(el => el.TYPE == '外销');
            let sumKeys = Object.keys(axOutDatas[0]).filter(key => key.indexOf('20') != -1);
            let sumObject = {};
            // 求对象数组所有属性的和
            for (let i = 0; i < sumKeys.length; i++) {
              sumObject[sumKeys[i]] = 0;
              for (let j = 0; j < axOutDatas.length; j++) {
                sumObject[sumKeys[i]] += axOutDatas[j][sumKeys[i]];
              }
            }
            axResultDatas.push({ ...axOutDatas[0], ...sumObject, PRODUCT: '' });

            //#endregion

            //#region 精密

            // 精密的分内外销
            let jmDatas = data.filter(el => el.SYB == '精密');
            let jmResultDatas = [];

            // 精密的外销,全都加起来
            let jmOutDatas = jmDatas.filter(el => el.TYPE == '外销');
            let sumJmOutObject = {};
            // 求对象数组所有属性的和
            for (let i = 0; i < sumKeys.length; i++) {
              sumJmOutObject[sumKeys[i]] = 0;
              for (let j = 0; j < jmOutDatas.length; j++) {
                sumJmOutObject[sumKeys[i]] += jmOutDatas[j][sumKeys[i]];
              }
            }
            jmResultDatas.push({ ...jmOutDatas[0], ...sumJmOutObject, PRODUCT: '' });

            // 精密的内销,全都加起来
            let jmInDatas = jmDatas.filter(el => el.TYPE == '内销');
            let sumJmInObject = {};
            // 求对象数组所有属性的和
            for (let i = 0; i < sumKeys.length; i++) {
              sumJmInObject[sumKeys[i]] = 0;
              for (let j = 0; j < jmInDatas.length; j++) {
                sumJmInObject[sumKeys[i]] += jmInDatas[j][sumKeys[i]];
              }
            }
            jmResultDatas.push({ ...jmInDatas[0], ...sumJmInObject, PRODUCT: '' });

            //#endregion

            data = data.filter(el => el.SYB !== '安信事业部' && el.SYB !== '精密');
            data.splice(0, 0, ...axResultDatas, ...jmResultDatas);
            //#endregion
            let xlsx = useMyXlsx();

            let replaceObj = {
              'SYB': '事业部',
              'PRODUCT': '产品',
              'TYPE': '内/外销',
              'YEAR': '年份',
              // 'AVG_SUM': '平均',
              // 'COUNT': '数量',
            };
            let hideColumns = ['SYB1', 'PRODUCT1', 'TYPE1', 'AVG_SUM', 'COUNT'];
            let exportOption = {
              titles: replaceObj,
              header: [],
              hideColumns: hideColumns,
            };
            let keys = Object.keys(data[0]);
            for (let i = 0; i < keys.length; i++) {
              let key = keys[i];
              //不需要隐藏,而且没有初始列名的key,直接用key当列名
              if (!hideColumns.includes(key) && !exportOption.titles[key]) {
                exportOption.titles[key] = key;
              }
              exportOption.header.push(key);
            }
            let now = tableDatas.exportYear + '年报表';
            xlsx.exportDatas(data, exportOption, now + '.xlsx');
          }
          else {
            showWarning('数据查询失败res' + res);
          }
        }).catch(err => {
          showWarning('导出失败err' + err);
        });
      },
      //包车数据
      bcDatas: []
    });

    return {
      loading,
      dataTableDialog,
      deleteIds, userid,
      buttonClicks,
      dialogDatas,
      tableDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

